<html>
<head>
<script type="text/javascript">
var logging = false;
var parentId = -1;
var mapMenu = [];
var DEL_MARK = "#del#";
var BLANK_URL = "about:blank";

function Note(id){
    this.id = id;
    var newArray = id.split(';');
    this.modified = new Date(parseInt(newArray[0]));
    this.url = unescape(newArray[1]);
    this.title = chrome.i18n.getMessage("title_date", this.modified.toLocaleDateString() + " " + this.modified.toLocaleTimeString());
    this.icon = "simple";
    if (this.url.length != 0) {
        this.title += "\n" + chrome.i18n.getMessage("title_url", this.url);
        this.icon = "linked";
    }
    this.selectionStart = 0;
    this.selectionEnd = 0;
    this.text = getItem(id);
    if (this.text == null) {
        this.text = "";
    };
    this.Html = function(len){
        var escaped = this.text;
        if (escaped != null && escaped != undefined && escaped != "") {
            var newArray = escaped.split('\n');
            for (var i = 0; i < newArray.length; i++) {
                if (newArray[i].length > 0) {
                    if (newArray[i].length > len) {
                        escaped = newArray[i].substr(0, len);
                    }
                    else {
                        escaped = newArray[i];
                    }
                    break;
                }
            }
        }
        var findReplace = [[/&/g, "&amp;"], [/</g, "&lt;"], [/>/g, "&gt;"], [/\"/g, "&quot;"]];
        for (var i = 0; i < findReplace.length; i++) {
            escaped = escaped.replace(findReplace[i][0], findReplace[i][1]);
        }
        return escaped;
    };
    this.ItemContent = function(){
        return '<span class="' + this.icon + '">' + this.Html(50) + '</span><div class="delete" onclick="notes.RemoveNote($(this).parent().attr(\'id\'))"></div>';
    };
    this.Item = function(){
        return '<div title="' + this.title + '" class="note" id="' + this.id +
        '" ondblclick="notes.SelectNoteAndGo(this.id);" onclick="notes.SelectNote(this.id);">' +
        this.ItemContent() +
        '</div>';
    };
    this.Find = function(vals){
        for (var i = 0; i < vals.length; i += 1) {
            if (this.text.indexOf(vals[i]) === -1 && this.url.indexOf(vals[i]) === -1) {
                return false;
            }
        }
        return true;
    };
}

function removeItem(key){
    try {
        log("Inside removeItem:" + key);
        window.localStorage.removeItem(key);
		removeSubMenu(key);
    } 
    catch (e) {
        log("Error inside removeItem");
        log(e);
    }
    log("Return from removeItem" + key);
}

function setItem(key, value){
    try {
        log("Inside setItem:" + key + ":" + value);
        window.localStorage.removeItem(key);
        window.localStorage.setItem(key, value);
		if (key.indexOf(';') != -1){
			if(value == DEL_MARK) {
	        	removeSubMenu(key);
			}
			else{
				createSubMenu(key);
			}		
		}
    } 
    catch (e) {
        log("Error inside setItem");
        log(e);
    }
    log("Return from setItem" + key + ":" + value);
}

function getItem(key){
    var value;
    log('Get Item:' + key);
    try {
        value = window.localStorage.getItem(key);
    } 
    catch (e) {
        log("Error inside getItem() for key:" + key);
        log(e);
        value = "null";
    }
    log("Returning value: " + value);
    return value;
}

function clearStrg(){
    log('about to clear local storage');
    window.localStorage.clear();
    log('cleared');
}

function getAllKeys(){
    var list = [];
    try {
        for (var i = 0; i < window.localStorage.length; i++) {
            list[i] = window.localStorage.key(i);
        }
    } 
    catch (e) {
        log("Error inside getAllKeys()");
        log(e);
        value = "null";
    }
    log("Returning value: " + list);
    return list;
}

function addNote(url, text, date){
    var key = null;
    if (date) {
        key = date.getTime() + ";" + escape(url);
    }
    else {
        key = createKey(url);
    }
    setItem(key, text);
    return key;
}

function createKey(url){
    var currentDate = new Date();
    var key = currentDate.getTime() + ";" + escape(url);
    return key;
}

function onCopyToNote(info, tab){
    if (!info.selectionText || info.selectionText.length == 0) {
        return;
    }
    else {
        chrome.browserAction.setIcon({
            'path': 'images/notepad24hl.png'
        });
        addNote(tab.url, info.selectionText);
        setTimeout(function(){
            chrome.browserAction.setIcon({
                'path': 'images/notepad24.png'
            });
        }, 1000);
    }
}

function installMenu(){
    var createProperties = {
        "title": chrome.i18n.getMessage("copy_to_note"),
        "type": "normal",
        "contexts": ["selection"],
        "onclick": onCopyToNote
    };
	chrome.contextMenus.create(createProperties);
	updateMenu();
}

function updateMenu()
{
	for (var i = 0; i < mapMenu.length; i++) {
   		chrome.contextMenus.remove(mapMenu[i][1]);
	}
	mapMenu = [];
	if (parentId != -1){
		chrome.contextMenus.remove(parentId);
		parentId = -1
	}
    var createProperties2 = {
        "title": chrome.i18n.getMessage("insert_from_note"),
        "contexts": ["editable"]
    };
    parentId = chrome.contextMenus.create(createProperties2);
    log("ParentId:" + parentId);
    var allKeys = getAllKeys();
    allKeys.sort();
    for (var i = 0; i < allKeys.length; i++) {
        if (allKeys[i].indexOf(';') != -1) {
			createSubMenu(allKeys[i]);
        }
    }
};

function createSubMenu(noteId)
{
    var note = new Note(noteId);
    if (note.text == DEL_MARK) {
        return;
    }
	var title = note.text.substr(0, 30);
	if(title == ""){
		title = " ";
	}
    var mid = chrome.contextMenus.create({
        "title": title,
        "parentId": parentId,
        "contexts": ["editable"],
        "onclick": clickNote
    });
	mapMenu.push([note.id, mid]);
    log(chrome.extension.lastError);
};

function removeSubMenu(noteId)
{
    for (var i = 0; i < mapMenu.length; i++) {
		if (mapMenu[i][0] == noteId) {
			chrome.contextMenus.remove(mapMenu[i][1]);
			mapMenu[i][0] = "";
			mapMenu[i][1] = -1;
			break;
		}
	}
};

function clickNote(x, tab){
    log(tab);
    for (var i = 0; i < mapMenu.length; i++) {
        if (mapMenu[i][1] == x.menuItemId) {
            var note = new Note(mapMenu[i][0]);
			var txt = note.text.replace(/\\/gm, "\\\\");
            txt = txt.replace(/'/gm, "\\'");
			txt = txt.replace(/\n/gm, "\\n");
            var code = "var focused_el = document.activeElement;" +
            "if(focused_el != null && (focused_el.tagName.toLowerCase() == 'input' || focused_el.tagName.toLowerCase() == 'textarea')){	var text = focused_el.value; var start = focused_el.selectionStart;var end = focused_el.selectionEnd;" +
            "focused_el.value = text.substr(0, start) +'" + txt + "' + text.slice(end);	focused_el.selectionStart = start +"+ note.text.length +"; focused_el.selectionEnd = focused_el.selectionStart;}";
			log(code);
            chrome.tabs.executeScript(tab.id, {
                "allFrames": true,
                "code": code
            });
            break;
        }
    }
}


function log(txt){
    if (logging) {
        console.log(txt);
    }
}

installMenu();
</script>
</head>
</html>
